package com.cosin.service;

import com.cosin.model.vo.FileVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileService {

    @Value("${file.upload-path}")
    private String localPathDir;

    public FileVo upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        String localDir = localPathDir + datePath;
        File dirFile = new File(localDir);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileType =
                fileName.substring(fileName.lastIndexOf("."));
        String realFileName = uuid + fileType;

        String filePathAll = localDir + realFileName;
        File realFile = new File(filePathAll);
        file.transferTo(realFile);

        String virtualPath = datePath + realFileName;
        return new FileVo(virtualPath,realFileName);
    }
}
